package com.jiang.smartdangjian.tool;

import com.google.gson.Gson;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class HttpUtil {
    public static final OkHttpClient OK_HTTP_CLIENT = new OkHttpClient.Builder().build();

    public static final Gson GSON = new Gson();

    public static String BASE_URL = "http://192.168.1.100:10001";

    public static final MediaType MEDIA_TYPE = MediaType.parse("application/json");
    public static final MediaType FILE_TYPE = MediaType.parse("application/octet-stream");


    public static void get(String url, MyCallback callback) {
        Request request = new Request.Builder()
                .url(BASE_URL + url)
                .get()
                .build();

        OK_HTTP_CLIENT.newCall(request).enqueue(callback);
    }

    public static void get(String url, String token, MyCallback callback) {
        Request request = new Request.Builder()
                .url(BASE_URL + url)
                .get()
                .addHeader("Authorization", "Bearer " + token)
                .build();

        OK_HTTP_CLIENT.newCall(request).enqueue(callback);
    }

    public static void post(String url, Object o, MyCallback callback) {
        RequestBody requestBody = RequestBody.create(MEDIA_TYPE, GSON.toJson(o));
        Request request = new Request.Builder()
                .url(BASE_URL + url)
                .post(requestBody)
                .build();

        OK_HTTP_CLIENT.newCall(request).enqueue(callback);
    }

    public static void post(String url, String token, Object o, MyCallback callback) {
        RequestBody requestBody = RequestBody.create(MEDIA_TYPE, GSON.toJson(o));
        Request request = new Request.Builder()
                .url(BASE_URL + url)
                .post(requestBody)
                .addHeader("Authorization", "Bearer " + token)
                .build();

        OK_HTTP_CLIENT.newCall(request).enqueue(callback);
    }

    public static void put(String url, String token, Object o, MyCallback callback) {
        RequestBody requestBody = RequestBody.create(MEDIA_TYPE, GSON.toJson(o));
        Request request = new Request.Builder()
                .url(BASE_URL + url)
                .post(requestBody)
                .addHeader("Authorization", "Bearer " + token)
                .build();

        OK_HTTP_CLIENT.newCall(request).enqueue(callback);
    }
}
